package app.keter.portal.exp;

import app.keter.portal.base.BaseController;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.keter.framework.core.util.ConcurrentUtil;
import com.keter.framework.web.annotation.Sid;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * 验证框架的基础功能和一些实验性功能特性的方法
 */
@RestController
@RequestMapping("/public/exp/sid")
public class ExpSidController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ExpSidController.class);

    /**
     * 声明线程池
     */
    ListeningExecutorService service = ConcurrentUtil.service(5);

    /**
     * 通过拦截器自动添加header头
     * @param sid
     * @return
     */
    @GetMapping
    public String sid(@Sid Long sid) {
        logger.info("sid-0:{}",sid);
        JSONResult result1 = restTemplate.getForObject(services.getCommon() + "/exp/sid", JSONResult.class);
        //在同一个方法内连续发请求可以拿到同一个SID
        JSONResult result2 = restTemplate.getForObject(services.getCommon() + "/exp/sid", JSONResult.class);
        logger.info("sid-1:{},sid-2:{}", result1.data(), result2.data());
        Assert.isTrue(result1.data().equals(result2.data()) && result1.data().equals(sid), "连续请求时获取的SID不一致！");
        return "得到了一致的SID：" + result1.data();
    }

    /**
     * 验证新线程下如何保持sid一致
     * @param sid
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping(value = "/thread")
    public String sidInThread(@Sid Long sid) throws ExecutionException, InterruptedException {
        logger.info("sid-thread:{}",sid);
        String result = ConcurrentUtil.result(service,
                service.submit(() -> {
                    // 向URL中添加SID
                    JSONResult result3 = restTemplate.getForObject(services.getCommon() +"/exp/sid?message=in-thread-with-sid&x-sid="+sid, JSONResult.class);
                    logger.info("sid3 in thread:{}", result3.string());
                    return result3.string();
                })
        );
        logger.info("sid-in-thread:{}", result);
        Assert.isTrue(sid.toString().equals(result), "请求内新线程获取的SID与原请求不一致！");
        return "得到了一致的SID：" + result;
    }
}
